package com.david.videoapp.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.app.PictureInPictureParams
import android.content.Intent
import android.content.res.Configuration
import android.os.*
import android.view.*
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.david.core.utils.PreferenceUtils
import com.david.videoapp.ChannelBean
import com.david.videoapp.R
import com.david.videoapp.VideoApplication
import com.david.videoapp.adapter.ChannelAdapter
import com.david.videoapp.hlsfunc.M3u8LinkGetActivity
import java.util.*

/**
 * TODO 判断是否是手机，是手机时添加支持小窗逻辑，电视时不需要支持;接收手机指令换台（通过tvHelper接收指令）
 * */
abstract class BaseVideoActivity: Activity() , ChannelAdapter.OnChannelSelectListener{
    var channelAdapter: ChannelAdapter = ChannelAdapter()

    private lateinit var channels: RecyclerView
    private lateinit var channelShowIcon: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_base_video)

        channels = findViewById(R.id.channels)
        channelShowIcon = findViewById(R.id.channel_show_icon)

        val params = FrameLayout.LayoutParams(resources.displayMetrics.widthPixels,FrameLayout.LayoutParams.MATCH_PARENT)
        params.gravity = Gravity.CENTER//videoView宽度不可修改，设置gravity实现居中
        findViewById<ViewGroup>(R.id.root).addView(getVideoView(), 0, params)

        channels.adapter = channelAdapter
        channelAdapter.onChannelSelectListener = this

        val lastPosition = PreferenceUtils.getInstance().getInt("lastPosition", 0)
        if (lastPosition != null) {
            channelAdapter.currentPosition = lastPosition
        }
        channelAdapter.setChannels(getChannels())


        var scrollPosition = (lastPosition.minus(7))
        if (scrollPosition < 0) {
            scrollPosition = 0
        }
        channels.scrollToPosition(scrollPosition)


        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val controller = window.decorView.windowInsetsController
            controller?.hide(WindowInsets.Type.systemBars())
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val controller = window.decorView.windowInsetsController
                controller?.hide(WindowInsets.Type.systemBars())
            } else {
                window.setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN
                )
            }
        }

        if (!VideoApplication.getApp().isTv) {
            //手机上隐藏显示频道逻辑
            channelShowIcon.setOnClickListener {
                if (channels.visibility == View.VISIBLE) {
                    channels.visibility = View.GONE
                    (channelShowIcon.layoutParams as ViewGroup.MarginLayoutParams).setMargins(0, 0, 0, 0)
                } else {
                    channels.visibility = View.VISIBLE
                    (channelShowIcon.layoutParams as ViewGroup.MarginLayoutParams).setMargins(0, 0, channels.width, 0)
                }
            }

            channelShowIcon.setOnLongClickListener {
                startActivity(Intent(this@BaseVideoActivity, M3u8LinkGetActivity::class.java))
                false
            }
        }
    }

    override fun onResume() {
        super.onResume()
        startPlay(channelAdapter.getCurrentChannel().url)
    }

    override fun onStop() {
        super.onStop()
        stopPlay()
    }

    override fun onDestroy() {
        super.onDestroy()
        stopPlay()
    }

    override fun onChannelSelect(position: Int, channelBean: ChannelBean) {
        startPlay(channelBean.url)

        PreferenceUtils.getInstance().setInt("lastPosition", position)
        PreferenceUtils.getInstance().setString("lastPlayTitle", channelBean.title)
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        val keyCode = event!!.keyCode
        return if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
            || keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN
            || keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
            event.dispatch(this, null, null)
        } else super.dispatchKeyEvent(event)
    }

    /**电视遥控器按下事件处理*/
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (VideoApplication.getApp().isTv) {//是Tv时在处理事件
            when (keyCode) {
                KeyEvent.KEYCODE_DPAD_UP -> {//如果按下的是上键
                    if (channelAdapter.currentPosition > 0) {
                        channelAdapter.currentPosition -= 1
                        channelAdapter.notifyItemChanged(channelAdapter.currentPosition+1)
                        channelAdapter.notifyItemChanged(channelAdapter.currentPosition)
                        onChannelSelect(channelAdapter.currentPosition, channelAdapter.getCurrentChannel())

                        var scrollPosition = channelAdapter.currentPosition - 7
                        scrollPosition = if (scrollPosition < 0) 0 else scrollPosition

                        channels.scrollToPosition(scrollPosition)
                    }
                }
                KeyEvent.KEYCODE_DPAD_DOWN -> {//如果按下的是下键
                    if (channelAdapter.currentPosition < channelAdapter.itemCount) {
                        channelAdapter.currentPosition += 1
                        channelAdapter.notifyItemChanged(channelAdapter.currentPosition-1)
                        channelAdapter.notifyItemChanged(channelAdapter.currentPosition)
                        onChannelSelect(channelAdapter.currentPosition, channelAdapter.getCurrentChannel())


                        var scrollPosition = channelAdapter.currentPosition + 7
                        scrollPosition = if (scrollPosition >= channelAdapter.itemCount) (channelAdapter.itemCount - 1) else scrollPosition

                        channels.scrollToPosition(scrollPosition)
                    }
                }
                KeyEvent.KEYCODE_DPAD_LEFT -> //如果按下的是左键
                    channels.visibility = View.VISIBLE
                KeyEvent.KEYCODE_DPAD_RIGHT -> //如果按下的是右键
                    channels.visibility = View.GONE
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    //防止连续切换
    var currentUrl = ""
    private val handler = @SuppressLint("HandlerLeak")
    object : Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (isPlaying()) {
                stopPlay()
            }
            setVideoPath(currentUrl)
            playVideo()
        }
    }

    private fun startPlay(url: String) {
        if (url == currentUrl) {
            return
        }
        currentUrl = url
        handler.removeMessages(0)
        handler.sendEmptyMessageDelayed(0, 1000)
    }


    private var lastBackTime:Long = 0
    override fun onBackPressed() {
        if ((System.currentTimeMillis() - lastBackTime) > 1000) {
            Toast.makeText(this, "双击退出程序", Toast.LENGTH_LONG).show()
        } else {
            super.onBackPressed()
        }
        lastBackTime = System.currentTimeMillis()
    }

    abstract fun getVideoView(): View

    abstract fun getChannels(): ArrayList<ChannelBean>

    abstract fun setVideoPath(videoPath:String)
    abstract fun playVideo()
    abstract fun pauseVideo()
    abstract fun stopPlay()
    abstract fun isPlaying():Boolean


    override fun onUserLeaveHint() {//点击home或者任务按钮进入小窗
        super.onUserLeaveHint()
        if (!VideoApplication.getApp().isTv) {
            enterPictureInPictureMode(PictureInPictureParams.Builder().build())
        }
    }

    override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean,
        newConfig: Configuration?) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
        if (!VideoApplication.getApp().isTv){
            if (isInPictureInPictureMode) {
                channelShowIcon.visibility = View.GONE
                channels.visibility = View.GONE
            } else {
                channelShowIcon.visibility = View.VISIBLE
                (channelShowIcon.layoutParams as ViewGroup.MarginLayoutParams).setMargins(0, 0, 0, 0)
            }
        }
    }
}